package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.OrderDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("支付成功");
    }


    /**
     * 订单分页显示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        log.info("page={},pageSize={}", page, pageSize);

        //构建分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //排序条件
        lambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        //执行分页查询
        orderService.page(pageInfo, lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();

        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(item, orderDto);

            Long id = item.getId();//分类id
            //根据id查询分类对象
            Orders orders = orderService.getById(id);

            //获取当前订单号
            String number=orders.getNumber();
            //获取当前订单详情
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,number);
            List<OrderDetail> orderDetailList=orderDetailService.list(queryWrapper);

            //获取当前订单里有几件商品，每件商品有几件，并累加起来
            int num = 0;
            for (OrderDetail orderDetail : orderDetailList) {
                num+=orderDetail.getNumber().intValue();
            }
            orderDto.setSumNum(num);
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);

        return R.success(orderDtoPage);
    }

    /**
     * 后台订单管理页面分页显示
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,String beginTime,String endTime){
        log.info("page={},pageSize={},number={},beginTime={},endTime={}", page, pageSize, number, beginTime, endTime);

        //构建分页构造器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        lambdaQueryWrapper.like(!StringUtils.isEmpty(number),Orders ::getNumber,number );
        //
        if (beginTime!=null&&endTime!=null){
            lambdaQueryWrapper.ge(Orders ::getOrderTime,beginTime);
            lambdaQueryWrapper.le(Orders ::getOrderTime,endTime);
        }

        //排序条件
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        //执行分页查询
        orderService.page(pageInfo, lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoPage, "records");

        List<Orders> records = pageInfo.getRecords();

        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(item, orderDto);

            String name="用户"+item.getUserId();
            orderDto.setUserName(name);
            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);

        return R.success(orderDtoPage);
    }

    /**
     * 后台更改配送状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        Long id = orders.getId();
        Integer status = orders.getStatus();
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,id);
        Orders one = orderService.getOne(queryWrapper);
        one.setStatus(status);
        orderService.updateById(one);
        return R.success("派送成功");
    }

    /**
     * 再来一单，直接生成新订单
     * @param orders
     * @return
     */
//    @PostMapping("/again")
//    public R<String> again(@RequestBody Orders orders){
//        log.info("orders:{}",orders);
//
//        //取得orderId
//        Long id = orders.getId();
//        Orders order = orderService.getById(id);
//        //设置订单号码
//        long orderId = IdWorker.getId();
//        orders.setId(orderId);
//        //设置订单号码
//        String number = String.valueOf(IdWorker.getId());
//        orders.setNumber(number);
//        //设置下单时间
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setCheckoutTime(LocalDateTime.now());
//        orders.setStatus(2);
//        //向订单表中插入一条数据
//        orderService.save(orders);
//        //修改订单明细表
//        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(OrderDetail::getOrderId,id);
//        List<OrderDetail> list = orderDetailService.list(queryWrapper);
//        list.stream().map((item)->{
//            //订单明细表id
//            long detailId = IdWorker.getId();
//            //设置订单号码
//            item.setOrderId(orderId);
//            item.setId(detailId);
//            return item;
//        }).collect(Collectors.toList());
//
//        //向订单明细表中插入多条数据
//        orderDetailService.saveBatch(list);
//        return R.success("再来一单");
//    }


    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        log.info("orders:{}",orders);

        //取得orderId
        Long id = orders.getId();
        Orders order = orderService.getById(id);
        //设置订单号码
        long orderId = IdWorker.getId();



        orders.setId(orderId);
        //设置订单号码
        String number = String.valueOf(IdWorker.getId());
        orders.setNumber(number);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        //向订单表中插入一条数据
        orderService.save(orders);
        //修改订单明细表
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        list.stream().map((item)->{
            //订单明细表id
            long detailId = IdWorker.getId();
            //设置订单号码
            item.setOrderId(orderId);
            item.setId(detailId);
            return item;
        }).collect(Collectors.toList());

        //向订单明细表中插入多条数据
        orderDetailService.saveBatch(list);
        return R.success("再来一单");
    }
}
